package com.mars.algorithm;

/**
 * @Author King
 * @create 2020/6/30 11:04
 */
public class KingLoopArrayQueue<T> {

    private T[] data;
    private int size;
    private int n;
    private int head;
    private int tail;

    public KingLoopArrayQueue(int capacity) {
        this.head = 0;
        this.tail = 0;
        this.data = (T[]) new Object[capacity];
        this.n = capacity;
    }

    public boolean enqueue(T d) {
        //队列满了
        if ((tail + 1) % n == head) {
            return false;
        }
        data[tail] = d;
        tail = (tail + 1) % n;
        size++;
        return true;
    }

    public T dequeue() {
        if (head == tail) {
            return null;
        }
        T t = data[head];
        head = (head + 1) % n;
        size--;
        return t;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        if (head == tail) {
            return true;
        }
        return false;
    }


    public static void main(String[] args) {
        KingLoopArrayQueue<String> queue = new KingLoopArrayQueue<String>(4);
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        System.out.println(queue.dequeue());
        System.out.println(queue.dequeue());
        System.out.println(queue.dequeue());
    }

}
